package com.dmcb.trade.business.crawlers.article;

import com.dmcb.common.business.utils.DateUtil;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.entities.Article;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Created by wangyong on 2017/8/16.
 */
@Service
public class AiFanErParser  extends BaseParser {

    /**
     * 网站URL网址
     *
     * @return 链接
     */
    @Override
    protected String url() {
        return CrawlConstant.AIFANER_URL;
    }

    /**
     * 获取标题选择器
     *
     * @return 标题选择器
     */
    @Override
    protected String titleSelect() {
        return "h1.c-single-normal__title,h1.c-article-header__title";
    }

    /**
     * 获取日期选择器
     *
     * @return 发布日期选择器
     */
    @Override
    protected String dateSelect() {
        return "span.c-article-header-meta__time";
    }

    /**
     * 获取正文内容选择器
     *
     * @return 正文内容选择器
     */
    @Override
    protected String bodySelect() {
        return "article.o-single-content__body__content,article.c-article-content__body";
    }

    /**
     * 获取封面选择器
     *
     * @return 封面选择器
     */
    @Override
    protected String coverSelect() {
        return "article.o-single-content__body__content>p img[src],article.c-article-content__body>p img[src]";
    }

    /**
     * 获取作者选择器
     *
     * @return 作者选择器
     */
    @Override
    protected String authorNameSelect() {
        return "p.c-card-author__name,span.o-article-header__author__name";
    }

    /**
     * 设置发布时间
     *
     * @param doc     网页
     * @param article 文章
     */
    @Override
    protected void setPostDate(Document doc, Article article) {
        Element element = doc.select(dateSelect()).first();
        String time = element.text();
        Date date  = new Date();
        if(StringUtils.isBlank(time)){
            article.setPostTime(date);
        }else{
            int field=0;
            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));    //获取东八区时间
            SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd ");
            if(time.contains("前天")){
                field = Calendar.DATE;
                c.add(field,-2);
                time = time.replace("前天","");
            }
            String curDate = s.format(c.getTime());  //当前日期
            date = DateUtil.parseDate(curDate+time);
        }

        article.setPostTime(date);
    }

    @Override
    protected String platform() {
        return "爱范儿";
    }
}
